package com.nlgc365.designpattern.Chapter04_Pattern.Struct.P01_Proxy.DynamicProxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.TimeUnit;

/**
 * 作用: 针对某一个附加功能的代理类
 * 动态代理: 不用像静态代理, 为每一个需要增强的具体类都创建一个代理类
 */
public class SomeServiceProxy {
    private static final Logger logger = LoggerFactory.getLogger(SomeServiceProxy.class);

    //获取代理类
    public ISomeService getProxy(ISomeService concernSomeService) {
        ISomeService proxyInstance = (ISomeService) Proxy.newProxyInstance(concernSomeService.getClass().getClassLoader(), concernSomeService.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                logger.info("SomeServiceProxy in");
                Object result = null;
                if (method.getName().equals("service")) {
                    long start = System.currentTimeMillis();
                    result = method.invoke(concernSomeService, args);
                    // Used to simulate real io services.
                    TimeUnit.SECONDS.sleep(1);
                    long end = System.currentTimeMillis();
                    logger.info("TimeWasted: {}ms", (end - start));
                }
                logger.info("SomeServiceProxy out");
                return result;
            }
        });
        return proxyInstance;
    }
}
